/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.groupbuy.comment.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.enums.OfflineHandleEventStatus;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.ProductMapper;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupActivityDto;
import com.yami.shop.groupbuy.comment.dao.GroupActivityMapper;
import com.yami.shop.groupbuy.comment.dto.GroupActivityDto;
import com.yami.shop.groupbuy.comment.enums.ActivityStatusEnum;
import com.yami.shop.groupbuy.comment.enums.GroupActivityStatusEnum;
import com.yami.shop.groupbuy.comment.model.GroupActivity;
import com.yami.shop.groupbuy.comment.model.GroupTeam;
import com.yami.shop.groupbuy.comment.service.GroupActivityService;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import com.yami.shop.groupbuy.comment.service.GroupTeamService;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 拼团活动表
 *
 * @author LGH
 * @date 2019-08-27 17:55:57
 */
@Service
@RequiredArgsConstructor
public class GroupActivityServiceImpl extends ServiceImpl<GroupActivityMapper, GroupActivity> implements GroupActivityService {

    private final GroupActivityMapper groupActivityMapper;
    private final ProductService productService;
    private final ProductMapper productMapper;
    private final GroupTeamService groupTeamService;
    private final GroupProdService groupProdService;
    private final OfflineHandleEventService offlineHandleEventService;


    /**
     * 获取分页列表
     *
     * @param page             分页对象
     * @param groupActivityDto 拼团活动
     * @return 分页对象
     */
    @Override
    public IPage<GroupActivityDto> getGroupActivityPage(PageParam<GroupActivityDto> page, GroupActivityDto groupActivityDto) {
        return groupActivityMapper.getGroupActivityPage(page, groupActivityDto);
    }

    /**
     * 获取拼团活动信息
     *
     * @param groupActivityId 拼团活动ID
     * @param prodId          商品ID
     * @return Api活动对象
     */
    @Override
    // @Cacheable(cacheNames = "groupActivityInfo", key = "#groupActivityId+':' + #prodId")
    public ApiGroupActivityDto getApiGroupActivityInfo(Long groupActivityId, Long prodId) {
        return groupActivityMapper.getApiGroupActivityInfo(groupActivityId, prodId);
    }

    /**
     * 移除拼团活动缓存
     */
    @CacheEvict(cacheNames = "groupActivityInfo", key = "#groupActivityId+':' + #prodId")
    public void removeGroupActivityInfoCache(Long groupActivityId, Long prodId) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Product> invalidGroupActivity(GroupActivity groupActivity) {
        // 获取未成团的团队
        List<GroupTeam> groupTeamList = groupTeamService.getNotGroupTeamsByActivityId(groupActivity.getGroupActivityId());

        // 处理未成团的拼团团队
        for (GroupTeam groupTeam : groupTeamList) {
            groupTeamService.updateNotGroupTeam(groupTeam);
        }

        // 更新活动状态
        groupActivity.setStatus(0);
        groupActivity.setUpdateTime(new Date());
        groupActivityMapper.updateById(groupActivity);

        List<Product> productList = productMapper.listByActivityId(Collections.singletonList(groupActivity.getGroupActivityId()));

        // 更新所有商品为未参团状态
        productMapper.updateToUnGroupByGroupActivityId(groupActivity.getGroupActivityId());
        return productList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditGroupActivity(OfflineHandleEventAuditParam offlineHandleEventAuditParam, Long sysUserId) {
        // 审核通过
        if (Objects.equals(offlineHandleEventAuditParam.getStatus(), OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue())) {
            // 更新拼团活动为未开启状态
            groupActivityMapper.updateStatus(offlineHandleEventAuditParam.getHandleId(), GroupActivityStatusEnum.DISABLE.value());
        }
        // 审核不通过
        else if (Objects.equals(offlineHandleEventAuditParam.getStatus(), OfflineHandleEventStatus.DISAGREE_BY_PLATFORM.getValue())) {
            groupActivityMapper.updateStatus(offlineHandleEventAuditParam.getHandleId(), GroupActivityStatusEnum.OFFLINE.getCode());
        }

        offlineHandleEventService.auditOfflineEvent(offlineHandleEventAuditParam, sysUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offline(GroupActivity groupActivity, String offlineReason, Long sysUserId) {

        // 添加下线处理记录
        Date now = new Date();
        OfflineHandleEvent offlineHandleEvent = new OfflineHandleEvent();
        offlineHandleEvent.setHandleId(groupActivity.getGroupActivityId());
        offlineHandleEvent.setHandleType(OfflineHandleEventType.GROUP_BUY.getValue());
        offlineHandleEvent.setCreateTime(now);
        offlineHandleEvent.setHandlerId(sysUserId);
        offlineHandleEvent.setOfflineReason(offlineReason);
        offlineHandleEvent.setStatus(OfflineHandleEventStatus.OFFLINE_BY_PLATFORM.getValue());
        offlineHandleEvent.setShopId(groupActivity.getShopId());
        offlineHandleEvent.setUpdateTime(now);
        offlineHandleEventService.save(offlineHandleEvent);

        // 如果活动为开始的状态
        if (Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.UNDER_WAY.value())) {
            // 获取未成团的团队
            List<GroupTeam> groupTeamList = groupTeamService.getNotGroupTeamsByActivityId(groupActivity.getGroupActivityId());
            if (CollectionUtil.isNotEmpty(groupTeamList)) {
                for (GroupTeam groupTeam : groupTeamList) {
                    groupTeamService.updateNotGroupTeam(groupTeam);
                }

            }
        }
        // 更新活动状态为违规下架
        groupActivityMapper.updateStatus(groupActivity.getGroupActivityId(), GroupActivityStatusEnum.OFFLINE.value());

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditApply(Long eventId, Long activityId, String reapplyReason) {
        // 更新活动为待审核状态
        groupActivityMapper.updateStatus(activityId, GroupActivityStatusEnum.WAIT_AUDIT.value());

        // 更新事件状态
        offlineHandleEventService.updateToApply(eventId, reapplyReason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeProdTypeByGroupActivityIdList(List<Long> groupActivityIds) {
        // 获取该活动下的所有商品
        List<Product> productList = productMapper.listByActivityId(groupActivityIds);
        groupActivityMapper.changeProdTypeByGroupActivityIdList(groupActivityIds);
        // 清除缓存
        for (Product product : productList) {
            productService.removeProdCacheByProdId(product.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
            productService.removeProdCacheByProdId(product.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
        groupActivityMapper.changeGroupActivityStatusByGroupActivityIdList(groupActivityIds);
        groupProdService.invalidGroupProdByActivityId(groupActivityIds);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateToDelete(Long groupActivityId) {
        // 更新活动为已删除状态
        groupActivityMapper.updateToDelete(groupActivityId);
        // 更新活动下的商品
        productMapper.updateToUnGroupByGroupActivityId(groupActivityId);
    }
}
